const express = require('express')
const multer = require('multer')
const fs = require('fs-extra')
const path = require('path')
const cors = require('cors')

const app = express()
const uploadDir = path.resolve(__dirname, 'uploads') // 上传目录

// 中间件
app.use(cors())
app.use(express.json())
app.use(express.urlencoded({ extended: true }))

// 初始化上传目录
fs.ensureDirSync(uploadDir)

// 查询已上传分片接口
app.get('/upload/status', async (req, res) => {
  const { fileHash } = req.query // 获取请求中的文件哈希
  const chunkDir = path.resolve(uploadDir, fileHash) // 构建分片目录路径

  try {
    // 检查文件哈希目录是否存在
    if (!fs.existsSync(chunkDir)) {
      return res.json({ uploadedChunks: [] }) // 返回空数组表示没有分片
    }

    // 读取分片目录中的所有文件
    const uploadedChunks = await fs.readdir(chunkDir)

    // 返回已上传的文件切片哈希
    res.json({ uploadedChunks })
  } catch (err) {
    console.error('Error fetching uploaded chunks:', err)
    res.status(500).json({ success: false })
  }
})

// 文件分片上传接口
app.post('/upload/chunk', multer().single('chunk'), async (req, res) => {
  const { chunkIndex, totalChunks, fileHash, fileChunkHash } = req.body
  const chunkDir = path.resolve(uploadDir, fileHash)
  // 确保分片目录存在
  await fs.ensureDir(chunkDir)
  const chunkPath = path.resolve(chunkDir, chunkIndex)
  // const chunkPath = path.resolve(chunkDir, `chunk_${chunkIndex}_${fileChunkHash}`)
  try {
    // 保存分片
    await fs.writeFile(chunkPath, req.file.buffer)
    res.json({ success: true })
  } catch (err) {
    console.error('Error saving chunk:', err)
    res.status(500).json({ success: false })
  }
})

// 合并分片接口
app.post('/upload/merge', async (req, res) => {
  const { fileHash, fileName } = req.body
  const chunkDir = path.resolve(uploadDir, fileHash) // 分片目录
  const filePath = path.resolve(uploadDir, fileName) // 合并后的文件路径

  try {
    // 读取分片文件夹中的所有分片文件
    const chunkFiles = await fs.readdir(chunkDir)
    chunkFiles.sort((a, b) => Number(a) - Number(b)) // 按序号排序

    // 创建写入流
    const writeStream = fs.createWriteStream(filePath)

    // 逐个读取分片文件并写入合并文件
    for (const chunkFile of chunkFiles) {
      const chunkPath = path.resolve(chunkDir, chunkFile) // 获取分片文件的完整路径
      const chunkBuffer = await fs.readFile(chunkPath) // 读取分片文件
      writeStream.write(chunkBuffer) // 写入合并文件
    }
    writeStream.end() // 结束写入流

    // 确保写入完成后再删除分片目录
    writeStream.on('finish', async () => {
      await fs.remove(chunkDir) // 删除分片目录
      res.json({ success: true, message: 'File merged successfully' })
    })
  } catch (err) {
    console.error('Error merging file:', err)
    res.status(500).json({ success: false })
  }
})

// 启动服务
const PORT = 3200
app.listen(PORT, () => {
  console.log(`Server running at http://localhost:${PORT}`)
})
